<?php
/**
 * DBERP 进销存系统
 *
 * ==========================================================================
 * @link      http://www.dberp.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   http://www.dberp.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Service;

use Doctrine\ORM\EntityManager;
use Sales\Entity\SalesOrderGoods;
use Sales\Entity\SalesOrderGoodsReturn;
use Sales\Entity\SalesOrderReturn;
use Sales\Entity\SalesSendWarehouseGoods;

class SalesOrderGoodsReturnManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加退货商品
     * @param array $data
     * @param SalesOrderReturn $salesOrderReturn
     * @return array
     * @throws \Doctrine\ORM\Exception\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     * @throws \Doctrine\Persistence\Mapping\MappingException
     */
    public function addSalesOrderGoodsReturn(array $data, SalesOrderReturn $salesOrderReturn): array
    {
        $returnArray = [];
        $returnAmount= 0;
        $goodsReturnAmount  = 0;
        $goodsReturnTax     = 0;
        foreach ($data['salesGoodsId'] as $salesGoodsId) {
            $goodsInfo = $this->entityManager->getRepository(SalesOrderGoods::class)->findOneBy(['salesGoodsId' => $salesGoodsId, 'salesOrderId' => $salesOrderReturn->getSalesOrderId()]);
            if($goodsInfo) {
                $goodsReturn = new SalesOrderGoodsReturn();
                $goodsReturn->setGoodsReturnId(null);
                $goodsReturn->setSalesOrderReturnId($salesOrderReturn->getSalesOrderReturnId());
                $goodsReturn->setSalesGoodsId($goodsInfo->getSalesGoodsId());
                $goodsReturn->setGoodsName($goodsInfo->getGoodsName());
                $goodsReturn->setGoodsNumber($goodsInfo->getGoodsNumber());
                $goodsReturn->setGoodsSpec($goodsInfo->getGoodsSpec());
                $goodsReturn->setGoodsUnit($goodsInfo->getGoodsUnit());
                $goodsReturn->setSalesGoodsPrice($goodsInfo->getSalesGoodsPrice());
                $goodsReturn->setSalesGoodsTax($goodsInfo->getSalesGoodsTax());
                $goodsReturn->setGoodsReturnNum($data['goodsReturnNum'][$salesGoodsId]);
                $goodsReturn->setGoodsReturnAmount($data['goodsReturnAmount'][$salesGoodsId]);

                if (!empty($data['goodsSerialNumber'][$goodsInfo->getSalesGoodsId()])) {
                    $goodsReturn->setGoodsSerialNumberStr(implode(',', array_filter($data['goodsSerialNumber'][$goodsInfo->getSalesGoodsId()])));
                }

                $returnAmount       = $returnAmount + $data['goodsReturnAmount'][$salesGoodsId];
                $goodsReturnAmount  = $goodsReturnAmount + $data['goodsReturnAmount'][$salesGoodsId];
                $goodsReturnTax     = $goodsReturnTax + $goodsInfo->getSalesGoodsPrice() * $data['goodsReturnNum'][$salesGoodsId] * $goodsInfo->getSalesGoodsTax() * 0.01;
                $returnArray['salesGoods'][] = [
                    'salesOrderId'      => $salesOrderReturn->getSalesOrderId(),
                    'salesGoodsId'      => $salesGoodsId,
                    'goodsReturnNum'    => $data['goodsReturnNum'][$salesGoodsId],
                    'goodsReturnAmount' => $data['goodsReturnAmount'][$salesGoodsId]
                ];

                $this->entityManager->persist($goodsReturn);
                $this->entityManager->flush();
                $this->entityManager->clear(SalesOrderGoodsReturn::class);

                if (!empty($data['goodsSerialNumber'][$goodsInfo->getSalesGoodsId()])) {
                    $warehouseGoodsInfo = $this->entityManager->getRepository(SalesSendWarehouseGoods::class)->findOneBy(['goodsId' => $goodsInfo->getGoodsId(), 'salesOrderId' => $goodsInfo->getSalesOrderId()]);
                    $goodsSerialArray = array_filter(explode(",", $warehouseGoodsInfo->getGoodsSerialNumberStr()));
                    $array = [];
                    if (!empty($goodsSerialArray)) foreach ($goodsSerialArray as $serialValue) {
                        if (!in_array($serialValue, $data['goodsSerialNumber'][$goodsInfo->getSalesGoodsId()])) $array[] = $serialValue;
                    }
                    $warehouseGoodsInfo->setGoodsSerialNumberStr(!empty($array) ? implode(",", $array) : '');
                    $this->entityManager->flush();
                }

            }
        }

        $returnArray['returnAmount']        = $returnAmount;
        $returnArray['goodsReturnAmount']   = $goodsReturnAmount;
        $returnArray['goodsReturnTax']      = $goodsReturnTax;
        return $returnArray;
    }

    /**
     * 删除退货商品
     * @param SalesOrderGoodsReturn $salesOrderGoodsReturn
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteSalesOrderGoodsReturn(SalesOrderGoodsReturn $salesOrderGoodsReturn): bool
    {
        if (!empty($salesOrderGoodsReturn->getGoodsSerialNumberStr())) {
            $salesGoods = $this->entityManager->getRepository(SalesOrderGoods::class)->findOneBy(['salesGoodsId' => $salesOrderGoodsReturn->getSalesGoodsId()]);
            if ($salesGoods) {
                $warehouseGoodsInfo = $this->entityManager->getRepository(SalesSendWarehouseGoods::class)->findOneBy(['goodsId' => $salesGoods->getGoodsId(), 'salesOrderId' => $salesGoods->getSalesOrderId()]);
                $warehouseGoodsInfo->setGoodsSerialNumberStr(empty($warehouseGoodsInfo->getGoodsSerialNumberStr()) ? $salesOrderGoodsReturn->getGoodsSerialNumberStr() : $warehouseGoodsInfo->getGoodsSerialNumberStr() . ',' . $salesOrderGoodsReturn->getGoodsSerialNumberStr());
                $this->entityManager->flush();
            }
        }

        $this->entityManager->remove($salesOrderGoodsReturn);
        $this->entityManager->flush();

        return true;
    }
}